﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waker.Common;
using System.Text.RegularExpressions;
using Waker.Entitys;
using Waker.APIs.ADS;
using Waker.APIs.NVR;

namespace Waker.Devices
{
    public partial class FormDeveicSubEdit : Base.FormBasePop
    {
        DataRow _DrSource;
        DataTable _DtNVR;
        ADSHalDataStruct.ADS_CommunicationParameter _Com;
        public FormDeveicSubEdit(string subId, ADSHalDataStruct.ADS_CommunicationParameter m_comm)
        {
            InitializeComponent();
            _DrSource = new BAL.BAL_Device().GetLSubDeviceById(subId).Rows[0];
            _Com = m_comm;
        }

        private void FormDeveicSubEdit_Load(object sender, EventArgs e)
        {
            //_DtNVR = new BAL.BAL_Device().GetTableByTableName("T_NVR");
            //ControlUtil.FillImageComboBox(_DtNVR, icbNVR_ID, "NVR_Name", "NVR_ID");

            //icbNVR_ID.EditValue = _DrSource["NVR_ID"] == DBNull.Value ? 0 : _DrSource["NVR_ID"];
            speOpenTime.Value = _DrSource["OpenTime"] == DBNull.Value ? 6 : Convert.ToInt32(_DrSource["OpenTime"]);
            speOpenTimeOut.Value = _DrSource["OpenTimeOut"] == DBNull.Value ? 6 : Convert.ToInt32(_DrSource["OpenTimeOut"]);
            chkIsUseNVR.Checked = _DrSource["IsUseNVR"] == DBNull.Value ? false : Convert.ToBoolean(_DrSource["IsUseNVR"]);
            //icbNVR_ID.Enabled = speNVRChannel.Enabled = chkIsUseNVR.Checked;

            txtNVRIp.Text = _DrSource["NVRIp"] == DBNull.Value ? string.Empty : _DrSource["NVRIp"].ToString();

            speNVRPort.Value = _DrSource["NVRPort"] == DBNull.Value ? 8000 : Convert.ToInt32(_DrSource["NVRPort"]);
            speNVRChannel.Value = _DrSource["NVRChannel"] == DBNull.Value ? 33 : Convert.ToInt32(_DrSource["NVRChannel"]);

            txtNVRUsrName.Text = _DrSource["NVRUsrName"] == DBNull.Value ? "admin" : _DrSource["NVRUsrName"].ToString();
            txtNVRPwd.Text = _DrSource["NVRPwd"] == DBNull.Value ? "12345" : _DrSource["NVRPwd"].ToString();

            txtLSubDevice_Name.Text = _DrSource["LSubDevice_Name"] == DBNull.Value ? string.Empty : _DrSource["LSubDevice_Name"].ToString();
            groupControl1.Enabled = chkIsUseNVR.Checked;
        }
        protected override void FormSave()
        {
            base.errorPop.ClearErrors();
            if (speOpenTime.Value < 1 || speOpenTime.Value > 10)
            {
                base.errorPop.SetError(speOpenTime, "时间应在1秒和10秒之间");
                return;
            }
            if (speOpenTimeOut.Value < 1 || speOpenTimeOut.Value > 60)
            {
                base.errorPop.SetError(speOpenTimeOut, "时间应在1秒和60秒之间");
                return;
            }
            if (chkIsUseNVR.Checked)
            {
                if (string.IsNullOrEmpty(txtLSubDevice_Name.Text))
                {
                    base.errorPop.SetError(txtLSubDevice_Name, "名称不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(txtNVRIp.Text) || !IPHelper.CheckIPAddr(txtNVRIp.Text))
                {
                    base.errorPop.SetError(txtNVRIp, "设备IP格式不正确");
                    return;
                }
                if (speNVRChannel.Value < 1)
                {
                    base.errorPop.SetError(speNVRChannel, "NVR通道号不正确");
                    return;
                }
                if (speNVRPort.Value < 0 || speNVRPort.Value > 65535)
                {
                    base.errorPop.SetError(speNVRPort, "端口超出范围");
                    return;
                }
                if (string.IsNullOrEmpty(txtNVRUsrName.Text))
                {
                    base.errorPop.SetError(txtNVRUsrName, "NVR用户名不能为空");
                    return;
                }
                if (!string.IsNullOrEmpty(txtNVRPwd.Text))
                {
                    int pwd = -1;
                    if (!int.TryParse(txtNVRPwd.Text, out pwd) || pwd < 0)
                    {
                        base.errorPop.SetError(txtNVRPwd, "密码必须为数字,可以为空");
                        return;
                    }
                }
                //if (icbNVR_ID.EditValue == null || icbNVR_ID.EditValue == DBNull.Value)
                //{
                //    base.errorPop.SetError(icbNVR_ID, "请选择抓图使用的的设备");
                //    return;
                //}
                //检查NVR是否成功
                if (!Session.IsNVRInited)
                {
                    Session.IsNVRInited = HCNetSDK.NET_DVR_Init();
                    HCNetSDK.NET_DVR_SetConnectTime(5000, 1);
                }
                if (Session.IsNVRInited)
                {
                    //var drs = _DtNVR.Select("NVR_ID=" + icbNVR_ID.EditValue.ToString(), string.Empty);
                    //if (drs.Length < 1)
                    //{
                    //    UI.ShowError("NVR登录失败,请检查参数后重试.");
                    //    return;
                    //}
                    NET_DVR_DEVICEINFO_V30 dev = new NET_DVR_DEVICEINFO_V30();
                    int lUserID = -1;
                    for (int i = 0; i < 3; i++)
                    {
                        lUserID = HCNetSDK.NET_DVR_Login_V30(
                               txtNVRIp.Text,
                               (ushort)Convert.ToInt32(speNVRPort.Text),
                               txtNVRUsrName.Text,
                               txtNVRPwd.Text,
                                out dev);
                        if (lUserID != -1)
                            break;
                    }
                    if (lUserID == -1)
                    {
                        UI.ShowError("NVR登录失败,请检查参数后重试.");
                        return;
                    }
                }
                else
                {
                    UI.ShowError("NVR初始化失败,请稍后重试.");
                    return;
                }
            }

            //设置time
            //m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            //m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            //m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));
            ADSHalDataStruct.ADS_LogicSubDeviceAddress subAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress();
            subAddress.physicalSubDevAddr = 0;
            subAddress.logicSubDevNumber = Convert.ToByte(_DrSource["Physics_ID"].ToString());

            //ADSHalDataStruct.ADS_IoInformation m_curIOInfo = new ADSHalDataStruct.ADS_IoInformation();
            var LSubDevice_Type = Convert.ToByte(_DrSource["LSubDevice_Type"].ToString());
            //m_curIOInfo.ioNumber = Convert.ToUInt32(dr["LSubDevice_Type"].ToString());
            //m_curIOInfo.nIsAction = 1;

            //if (subAddress.logicSubDevNumber != 0 && m_curIOInfo.ioNumber != 0 && m_curIOInfo.nIsAction == 1)
            if (subAddress.logicSubDevNumber == 0)
            {
                UI.ShowError("门禁设备参数错误");
                return;
            }
            var LogicSubDeviceConfiguration = new ADSHalDataStruct.ADS_LogicSubDeviceConfiguration();
            LogicSubDeviceConfiguration.logicSubDeviceType = LSubDevice_Type;
            LogicSubDeviceConfiguration.doorConfigurattion = new ADSHalDataStruct.ADS_DoorConfiguration();
            LogicSubDeviceConfiguration.doorConfigurattion.isEnableSuperPassword = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.superPassword = 12345678;
            LogicSubDeviceConfiguration.doorConfigurattion.openAlarmTime = Convert.ToUInt32(speOpenTimeOut.Value) * 10;

            LogicSubDeviceConfiguration.doorConfigurattion.isCheckDoorSensor = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.readerType = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.workModeSwitchType = 0;
            var SubDevWorkMode = new ADSHalDataStruct.ADS_SubDevWorkMode();
            LogicSubDeviceConfiguration.doorConfigurattion.inWorkMode = SubDevWorkMode.outWorkMode;
            LogicSubDeviceConfiguration.doorConfigurattion.outWorkMode = SubDevWorkMode.outWorkMode;

            LogicSubDeviceConfiguration.doorConfigurattion.reserve1 = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.reserve2 = 0;
            int iResult = ADSHalAPI.ADS_SetLogicSubDeviceConfiguration(ref Session._ADS_Comadapter, ref _Com, ref subAddress, ref LogicSubDeviceConfiguration);
            //ADS_SetIoConfiguration
            var isOK = iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS;
            if (!isOK)
            {
                UI.ShowError("设置门开超时报警时间失败");
                return;
            }


            ADSHalDataStruct.ADS_IoAddress ioAddress = new ADSHalDataStruct.ADS_IoAddress();
            ioAddress.ioNumber = LSubDevice_Type;

            var IoConfiguration = new ADSHalDataStruct.ADS_IoConfiguration();
            IoConfiguration.normalLevel = 0;
            IoConfiguration.openTime = Convert.ToUInt32(speOpenTime.Value) * 10;
            IoConfiguration.functionType = Convert.ToByte(ADSHalConstant.ADS_IoFunctionType.ADS_IOFT_DEFAULT);
            IoConfiguration.checkType = Convert.ToByte(ADSHalConstant.ADS_IoCheckType.ADS_IOCT_2_STATE);
            IoConfiguration.isPermanenceArm = 1;

            IoConfiguration.isFastAlarm = 1;
            IoConfiguration.upperLimitValue = 100;
            IoConfiguration.lowerLimitValue = 0;

            IoConfiguration.reserve = 0;

            //public uint upperLimitValue;		///< 下溢告警值，只有检测类型设置为模拟，才会产生上下溢告警，端口实际
            /////< 采集的电压数值低于该值就产生下溢告警。只对具有AD输入的端口有意义。
            //public uint lowerLimitValue;		///< 上溢告警值，端口实际采集的电压数值高于该值就产生上溢告警。只对具有AD输入的端口有意义。 

            iResult = ADSHalAPI.ADS_SetIoConfiguration(ref Session._ADS_Comadapter, ref _Com, ref subAddress, ref ioAddress, ref IoConfiguration);
            //ADS_SetIoConfiguration
            isOK = iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS;
            if (!isOK)
            {
                UI.ShowError("设置开门持续时间失败");
                return;
            }
            isOK = new BAL.BAL_Device().updateSubDeviceSetting(
               _DrSource["LSubDevice_ID"].ToString(),
               Convert.ToInt32(speOpenTime.Value),
               Convert.ToInt32(speOpenTimeOut.Value),
               chkIsUseNVR.Checked,
               txtNVRIp.Text.Trim(),
               Convert.ToInt32(speNVRChannel.Value),
               Convert.ToInt32(speNVRPort.Value),
               txtNVRUsrName.Text.Trim(),
               txtNVRPwd.Text
                );
            //isOK = new BAL.BAL_Device().updateSubDeviceSetting(
            //   _DrSource["LSubDevice_ID"].ToString(),
            //   Convert.ToInt32(speOpenTime.Value),
            //   Convert.ToInt32(speOpenTimeOut.Value),
            //   chkIsUseNVR.Checked,
            //   icbNVR_ID.EditValue == DBNull.Value ? 0 : Convert.ToInt32(icbNVR_ID.EditValue),
            //   Convert.ToInt32(speNVRChannel.Value),
            //   txtLSubDevice_Name.Text.Trim()
            //    );
            if (isOK)
            {
                UI.ShowInfo("保存并设置成功");
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                UI.ShowError("保存并设置失败");
            }
        }

        private void chkIsUseNVR_CheckedChanged(object sender, EventArgs e)
        {
            groupControl1.Enabled = chkIsUseNVR.Checked;
            //icbNVR_ID.Enabled = speNVRChannel.Enabled = chkIsUseNVR.Checked;
        }
    }
}
